package com.hbnu.controller;

import com.hbnu.anno.Log;
import com.hbnu.domain.Adobe;
import com.hbnu.domain.Book;
import com.hbnu.service.AdobeService;
import com.hbnu.service.BookService;
import com.hbnu.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @version: 1.0
 * @ClassName: Function
 * @Description: TODO
 * @Author: 86132
 * @Date: 2025/11/12 8:14
 */
@Component
public class Function {
    private static final ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    private static final AdobeService adobeService = (AdobeService) applicationContext.getBean("adobeService");
    private static final BookService bookService = (BookService) applicationContext.getBean("bookService");

    //删除用户预约
    @Transactional
    public void deleteBook(Integer id) {
        //查询预约,获取民宿id
        Book book =  bookService.searchById(id);
        //将民宿状态修改为可用
        Adobe adobe = adobeService.findById(book.getAdobeId());
        adobe.setStatus(1);
        adobeService.updateStatus(adobe);
        //删除预约
        bookService.deleteById(id);
    }

    //查看用户预约
    public void listByUserId(Integer userId) {
        List<Book> bookList = bookService.listByUserId(userId);
        for (Book book : bookList) {
            System.out.println("订单号: " + book.getId() +
                    ", 民宿号: " + book.getAdobeId() +
                    ", 入住日期: " + new SimpleDateFormat("yyyy-MM-dd").format(book.getCheckInDate()) +
                    ", 退房日期: " + new SimpleDateFormat("yyyy-MM-dd").format(book.getCheckOutDate()) +
                    ", 总金额: " + book.getTotalAmount());
        }
    }

    //预约民宿
    @Transactional
    public void book(Book book) {
        //获取金额
        Adobe adobe = adobeService.findById(book.getAdobeId());
        book.setTotalAmount(adobe.getPrice());
        //预约
        bookService.book(book);
        //修改民宿状态为不可用
        adobe.setStatus(0);
        adobeService.updateStatus(adobe);
    }

    //查看指定民宿
    public void searchOne(Integer id) {
        Adobe adobe = adobeService.findById(id);
        System.out.println(adobe);
    }

    //查看所有民宿
    public void searchAll() {
        List<Adobe> adobeList = adobeService.findAll();
        for (Adobe adobe : adobeList) {
            //只显示可入住的民宿
            if (adobe.getStatus() == 1) {
                System.out.println("序号：" + adobe.getId() +  ", 名称：" + adobe.getName() + ", 简介：" + adobe.getDescription());
            }
        }
    }
}
